"""
@author: j.l.liu
@create: 
@description: 中英文翻译，百度通用文本翻译，免费字符5万/月
"""
import tkinter as tk
from tkinter import ttk, messagebox
import requests, hashlib, random, os

APP_ID = "20250717002408958"
SECRET_KEY = '7PS10fWs6snBdILjpc2L'
BAIDU_URL = "https://fanyi-api.baidu.com/api/trans/vip/translate"

def translate(text, direction):
    if not text.strip():
        return ""
    src, dst = ("zh", "en") if direction == "zh2en" else ("en", "zh")
    salt = str(random.randint(10000, 99999))
    sign = hashlib.md5((APP_ID + text + salt + SECRET_KEY).encode()).hexdigest()
    params = {
        "q": text,
        "from": src,
        "to": dst,
        "appid": APP_ID,
        "salt": salt,
        "sign": sign
    }
    try:
        r = requests.post(BAIDU_URL, data=params, timeout=5)
        data = r.json()
        if "trans_result" not in data:
            return data.get("error_msg", "unknown error")
        return data["trans_result"][0]["dst"]
    except Exception as e:
        return str(e)

def on_translate():
    src_text = entry_src.get("1.0", "end-1c")
    direction = var_dir.get()
    res = translate(src_text, direction)
    entry_dst.delete("1.0", tk.END)
    entry_dst.insert("1.0", res)

root = tk.Tk()
root.title("双向翻译")
root.geometry("500x300")
root.resizable(False, False)
root.config(background="#D8F1BF")
# 输入
tk.Label(root, text="原文").pack(pady=2)
entry_src = tk.Text(root, height=5, width=60)
entry_src.pack(pady=2)

# 方向
var_dir = tk.StringVar(value="zh2en")
frame = ttk.Frame(root)
ttk.Radiobutton(frame, text="中文→英文", variable=var_dir, value="zh2en").pack(side="left")
ttk.Radiobutton(frame, text="英文→中文", variable=var_dir, value="en2zh").pack(side="left")
frame.pack(pady=5)

# 翻译按钮
ttk.Button(root, text="翻译", command=on_translate).pack(pady=5)

# 结果
tk.Label(root, text="翻译结果").pack(pady=2)
entry_dst = tk.Text(root, height=5, width=60)
entry_dst.pack(pady=2)

root.mainloop()